package com.ieng.kican.common.groups.captcha;

import com.ieng.kican.common.groups.captcha.domain.CaptchaAttrs;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;

import java.util.Random;

public class CaptchaCation {

    public static synchronized Action base64(final CaptchaAttrs attrs) {
        final Captcha captcha;
        final int width = attrs.getWidth();
        final int height = attrs.getHeight();

        switch (attrs.getType()) {
            case GIF:
                captcha = gif(width, height);
                break;
            case SPEC:
                captcha = spec(width, height);
                break;
            case CHINESE:
                captcha = chinese(width, height);
                break;
            case CHINESE_GIF:
                captcha = chineseGif(width, height);
                break;
            case ARITHMETIC:
                captcha = arithmetic(width, height);
                break;
            default:
                captcha = random(width, height);
                break;
        }

        return new Action(captcha.text(), captcha.toBase64());
    }

    private static Captcha gif(int width, int height) {
        return new GifCaptcha(width, height);
    }

    private static Captcha spec(int width, int height) {
        return new SpecCaptcha(width, height);
    }

    private static Captcha chinese(int width, int height) {
        return new ChineseCaptcha(width, height);
    }

    private static Captcha chineseGif(int width, int height) {
        return new ChineseGifCaptcha(width, height);
    }

    private static Captcha arithmetic(int width, int height) {
        return new ArithmeticCaptcha(width, height);
    }

    private static Captcha random(int width, int height) {
        int nextInt = new Random().nextInt(10);
        if (nextInt == 2) {
            return gif(width, height);
        } else if (nextInt == 5) {
            return chinese(width, height);
        } else if (nextInt == 7) {
            return chineseGif(width, height);
        } else if (nextInt == 9) {
            return spec(width, height);
        } else {
            return arithmetic(width, height);
        }
    }


    public static class Action {
        private final String text;
        private final String base64;

        public Action(String text, String base64) {
            this.text = text;
            this.base64 = base64;
        }

        public String getBase64() {
            return base64;
        }

        public String getText() {
            return text;
        }
    }

}
